package global.com.loansapplication.ui.actviity.login;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.jakewharton.rxbinding.view.RxView;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import global.com.loansapplication.R;
import global.com.loansapplication.base.BaseActivity;
import global.com.loansapplication.comm.Constants;
import global.com.loansapplication.comm.MyApplication;
import global.com.loansapplication.event.NetErrorEvent;
import global.com.loansapplication.ui.actviity.login.biz.CheckBiz;
import global.com.loansapplication.ui.actviity.login.component.DaggerCheckComponent;
import global.com.loansapplication.ui.actviity.login.contract.CheckContract;
import global.com.loansapplication.ui.actviity.login.module.CheckModule;
import global.com.loansapplication.ui.actviity.login.presenter.CheckPresenter;
import global.com.loansapplication.util.AlertUtils;
import global.com.loansapplication.util.LogUtils;
import rx.functions.Action1;


public class CheckAct extends BaseActivity implements CheckContract.View {


    @Bind(R.id.check_name)
    EditText name;//实名认证姓名
    @Bind(R.id.check_company)
    EditText company;//企业
    @Bind(R.id.check_phone)
    EditText phone;//企业电话
    @Bind(R.id.check_photo)
    ImageView photo;//照片
    @Bind(R.id.check_next)
    TextView next;//要交

    @Inject
    CheckPresenter presenter;

    @Inject
    CheckBiz biz;

    private AlertView photoPickerDialog;


    private FileInputStream is = null;
    List<String> photoInfos = new ArrayList<>();


    @Override
    protected void setRoot() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_check);
    }

    @Override
    protected void setup() {
        DaggerCheckComponent.builder().checkModule(new CheckModule(this)).build().inject(this);
        presenter.setBiz(biz);
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {

        setToolBar("完善资料", "#FE782F");
        Constants.activitys.add(this);
        RxView.clicks(photo)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        showImage();
                    }
                });

        RxView.clicks(next)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.upload(MyApplication.userInfo.getUserCode(), name.getText().toString().trim(), company.getText().toString().trim(), phone.getText().toString().trim(), photoInfos);
                    }
                });

    }

    @Override
    public void updateImages(List<Map<String, Object>> images) {

    }

    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }


    public void showImage() {
        if (photoPickerDialog == null) {
            photoPickerDialog = AlertUtils.photoPicker(CheckAct.this, GalleryFinal.copyGlobalFuncationConfig(),
                    new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            showPhote(resultList.get(0).getPhotoPath());
                            if(photoInfos.size()>0){
                                photoInfos.set(0, resultList.get(0).getPhotoPath());
                            }else{
                                photoInfos.add(0, resultList.get(0).getPhotoPath());
                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            LogUtils.d(requestCode + "", errorMsg);
                        }
                    });
        }
        photoPickerDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }

    private void showPhote(String path) {
        LogUtils.d(path);
        try {
            is = new FileInputStream(path);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
            photo.setImageBitmap(bitmap);
            photo.setScaleType(ImageView.ScaleType.FIT_XY);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
